<template>
    <div class="institutions_table">
        <!-- 搜索框、按钮布局 -->
        <div class="inputCont">
            <el-row :gutter="20" style="width:100%">
                <el-col :span="20">
                    <el-row>
                        <el-form style="width:100%" class="demo-form-inline" :inline="screen" label-width="60px">
                            <el-col :span="6">
                                <el-form-item label="姓名">
                                    <el-input maxlength="20" v-model="searchForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="账号">
                                    <el-input maxlength="20" v-model="searchForm.account"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="部门">
                                    <el-input maxlength="20" v-model="searchForm.unit"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-form>
                    </el-row>
                </el-col>
                <el-col :span="4">
                    <div style="display: flex;float: right">
                        <el-button type="primary" @click="getListData" size="large" style="float: right"
                            class="btn-class">查询</el-button>
                        <el-button class="btn-class" type="primary" style="float: right" @click="addNewOne"
                            size="large">增加</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>

        <el-table :data="treeTableJson" highlight-current-row border>
            <el-table-column type="index" width="50" align="center"></el-table-column>
            <el-table-column label="姓名" property="user_name" align="center"></el-table-column>
            <el-table-column label="登录账号" property="login_name" align="center"></el-table-column>
            <el-table-column label="角色" property="role_names" align="center"></el-table-column>
            <el-table-column label="部门" property="unit_name" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button @click="editNewOne(scope.row)" type="text" size="small" class="color_blue">修改</el-button>
                    <el-button @click="deleteOne(scope.row)" type="text" size="small" class="color_blue">删除</el-button>
                    <!-- <el-button
                        @click="operGxsb(scope.row)"
                        type="text"
                        size="small"
                        class="color_blue"
                    >工序设备</el-button>-->
                    <!-- <el-button
                        @click="resetOne(scope.row)"
                        type="text"
                        size="small"
                        class="color_blue"
                    >重置密码</el-button>
                    <el-button
                        @click="disableItem(scope.row)"
                        type="text"
                        size="small"
                        class="color_blue"
                    >{{scope.row.state == 0 ? '启用' : '禁用'}}</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <pagination :paginationData="paginationData" @paginationDataNew="paginationDataNew"
            v-if="this.paginationData.totalNum"></pagination>
        <!-- 新增弹窗 -->
        <el-dialog title="新增用户" :visible.sync="addshow" :close-on-click-modal="false" @close="dialogClose('addForm')">
            <el-form label-width="150px" :model="addForm" :rules="addRules" ref="addForm">
                <el-form-item label="姓名" prop="name">
                    <el-input maxlength="20" v-model="addForm.name" placeholder="请填写用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="登录账号" prop="login_name">
                    <el-input maxlength="20" v-model="addForm.login_name" placeholder="请填写登录账号"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="show_password">
                    <el-input maxlength="20" v-model="addForm.show_password" placeholder="请填写登录密码"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role_ids">
                    <el-select v-model="addForm.role_ids" style="width: 100%;" placeholder="请选择角色"
                        @remove-tag="removeAddTag" multiple>
                        <el-option v-for="item in roleJson" :key="item.role_id" :label="item.role_name"
                            :value="item.role_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="App环节" prop="turn_ids">
                    <el-select v-model="addForm.turn_ids" style="width: 100%;" placeholder="请选择App环节">
                        <el-option v-for="item in huanjieList" :key="item.turn_id" :label="item.turn_name"
                            :value="item.turn_id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="角色类型"
                      prop='user_type'>
          <el-select v-model="addForm.user_type"
                     style="width: 100%;"
                     placeholder="请选择角色类型">
            <el-option v-for="item in typeJson"
                       :key="item.codelist_id"
                       :label="item.code_name"
                       :value="item.code_value">
            </el-option>
          </el-select>
                </el-form-item>-->
                <el-form-item label="机构" prop="unit">
                    <el-input maxlength="20" v-model="addForm.unit" :disabled="true"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addshow = false" size="small">关 闭</el-button>
                <el-button class="btn-class" type="primary" @click="addcommit" size="small">保 存</el-button>
            </div>
        </el-dialog>
        <!-- ----------------------------------- -->
        <!-- 修改弹窗 -->
        <el-dialog title="用户修改" :visible.sync="editshow" :close-on-click-modal="false" @close="dialogClose('editForm')">
            <el-form label-width="150px" :model="editForm" :rules="addRules" ref="editForm">
                <el-form-item label="姓名" prop="name">
                    <el-input maxlength="20" v-model="editForm.name" placeholder="请填写用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="登录账号" prop="login_name">
                    <el-input maxlength="20" v-model="editForm.login_name" placeholder="请填写登录账号"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="show_password">
                    <el-input maxlength="20" v-model="editForm.show_password" placeholder="请填写登录密码"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role_ids">
                    <el-select v-model="editForm.role_ids" style="width: 100%;" placeholder="请选择角色"
                        @remove-tag="removeEditTag" multiple>
                        <el-option v-for="item in roleJson" :key="item.role_id" :label="item.role_name"
                            :value="item.role_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="App环节" prop="turn_ids">
                    <el-select v-model="editForm.turn_ids" style="width: 100%;" placeholder="请选择App环节">
                        <el-option v-for="item in huanjieList" :key="item.turn_id" :label="item.turn_name"
                            :value="item.turn_id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="角色类型"
                      prop='user_type'>
          <el-select v-model="editForm.user_type"
                     style="width: 100%;"
                     placeholder="请选择角色类型">
            <el-option v-for="item in typeJson"
                       :key="item.codelist_id"
                       :label="item.code_name"
                       :value="item.code_value">
            </el-option>
          </el-select>
                </el-form-item>-->
                <el-form-item label="机构" prop="unit">
                    <el-input maxlength="20" v-model="editForm.unit" :disabled="true"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editshow = false" size="small">关 闭</el-button>
                <el-button class="btn-class" type="primary" @click="editcommit" size="small">保 存</el-button>
            </div>
        </el-dialog>
        <!-- ----------------------------------- -->
        <!-- 重置密码弹窗 -->
        <el-dialog title="重置密码" :visible.sync="resetshow" :close-on-click-modal="false">
            <el-form label-width="100px" :model="resetForm" :rules="resetRules" ref="resetForm">
                <el-form-item label="新密码" prop="password">
                    <el-input maxlength="20" v-model="resetForm.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="passwordAgain">
                    <el-input maxlength="20" v-model="resetForm.passwordAgain"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetshow = false" size="small">取 消</el-button>
                <el-button class="btn-class" type="primary" @click="resetPass" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- ------------------------------ -->
        <!-- 工序设备 -->
        <!-- 新增弹窗 -->
        <el-dialog title="工序设备" :visible.sync="gxsbshow" :close-on-click-modal="false" @close="dialogClose('gxsbForm')">
            <div class="btn_container">
                <el-button type="primary" class="addItemBtn" icon="el-icon-plus" size="small" @click="addEmptyItem">
                </el-button>
            </div>
            <el-form :model="gxsbForm" ref="gxsbForm" label-width="100px">
                <el-table :data="gxsbForm.gxsbData" highlight-current-row border class="gxsbTable">
                    <el-table-column label="工序" align="center">
                        <template slot-scope="scope">
                            <el-form-item :prop="'gxsbData.' + scope.$index + '.turn_id'" :rules="[{ required: true }]"
                                :show-message="false">
                                <el-select v-model="scope.row.turn_id" style="width: 100%" placeholder filterable>
                                    <el-option v-for="item in turnList" :key="item.turn_id" :label="item.turn_name"
                                        :value="item.turn_id"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="设备" align="center">
                        <template slot-scope="scope">
                            <el-form-item :prop="
                                'gxsbData.' + scope.$index + '.device_id'
                            " :rules="[{ required: true }]" :show-message="false">
                                <el-select v-model="scope.row.device_id" style="width: 100%" placeholder filterable>
                                    <el-option v-for="item in deviceList" :key="item.device_id"
                                        :label="item.device_name_parm" :value="item.device_id"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="编辑" align="center" width="150">
                        <template slot-scope="scope">
                            <el-button @click="deleteGxsb(scope.row)" type="text" size="small" class="color_red">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="gxsbshow = false" size="small">取 消</el-button>
                <el-button class="btn-class" type="primary" @click="insertGxsb" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
const yesOrNo = [
    {
        code_name: "是",
        code_value: "1"
    },
    {
        code_name: "否",
        code_value: "0"
    }
];
import * as api from "@/http/admin-api.js";
import Bus from "./bus.js";
import pagination from "@/comon/components/pagination.vue";
import util from "@/utils/util";
export default {
    components: {
        pagination
    },
    data() {
        return {
            yesOrNo,
            flag: true,
            searchForm: {
                name: "",
                account: "",
                unit: ""
            },
            paginationData: {
                pageNum: "1",
                pageSize: "10",
                totalNum: ""
            },
            treeTableJson: [],
            tableId: "",
            tableName: "",
            roleJson: [],
            typeJson: [],
            addshow: false,
            addForm: {
                name: "",
                login_name: "",
                show_password: "",
                role_ids: [],
                turn_ids: "",
                // user_type: '',
                unit: ""
            },
            gxsbshow: false,
            gxsbForm: {
                gxsbData: []
            },
            roleString: "",
            turnString: "",
            addRules: {
                name: [
                    {
                        required: true,
                        message: "请填写用户姓名",
                        trigger: "blur"
                    }
                ],
                login_name: [
                    {
                        required: true,
                        message: "请填写登录账号",
                        trigger: "blur"
                    }
                ],
                show_password: [
                    {
                        required: true,
                        message: "请填写登录密码",
                        trigger: "blur"
                    }
                ],
                role_ids: [
                    {
                        required: true,
                        message: "请填写选择角色",
                        trigger: "change,blur"
                    }
                ],
                // turn_ids: [
                //     {
                //         required: true,
                //         message: "请选择所属环节",
                //         trigger: "change,blur"
                //     }
                // ],
                // user_type: [
                //     { required: true, message: '请填写选择角色类型', trigger: 'change,blur' }
                // ],
                unit: [
                    { required: true, message: "请选择机构", trigger: "blur" }
                ]
            },

            editshow: false,
            editForm: {
                name: "",
                login_name: "",
                show_password: "",
                role_ids: [],
                turn_ids: "",
                unit: "",
                // user_type: '',
                user_id: ""
            },
            resetshow: false,
            resetForm: {
                password: "",
                passwordAgain: "",
                user_id: ""
            },
            resetRules: {
                password: [
                    { required: true, message: "请输入新密码", trigger: "blur" }
                ],
                passwordAgain: [
                    { required: true, message: "请确认新密码", trigger: "blur" }
                ]
            },

            disableForm: {
                msg: "",
                user_id: "",
                state: ""
            },
            screenWidth: "",
            screen: true,
            turnList: [],
            deviceList: [],
            currentRow: null
        };
    },
    methods: {
        //通过unitid获取table主表
        getListData() {
            api.getListData({
                pageNum: this.paginationData.pageNum,
                pageSize: this.paginationData.pageSize,
                unit_id: this.tableId,
                query_user_name: this.searchForm.name,
                query_login_name: this.searchForm.account,
                query_unit_name: this.searchForm.unit
            }).then(res => {
                if (res) {
                    this.paginationData.pageNum = res.bus_json.pageNum;
                    this.paginationData.pageSize = res.bus_json.pageSize;
                    this.paginationData.totalNum = res.bus_json.totalNum;
                    this.treeTableJson = res.bus_json.items;
                }
            });
        },
        //总线获取unit_id，来自tree
        getTableId() {
            Bus.$on("unit_id", (tableId, tableName) => {
                this.tableId = tableId;
                this.tableName = tableName;
            });
        },
        //查询所属环节
        getHuanjie() {
            api.getTurnList({ type: 2 }).then(res => {
                if (res) {
                    this.huanjieList = res.bus_json;
                }
            });
        },
        //查询工序
        getTurnList(user_id) {
            api.getTurnListByUserId({ user_id: user_id }).then(res => {
                if (res) {
                    this.turnList = res.bus_json;
                }
            });
        },
        //查询设备
        getDeviceList() {
            api.getDevicePageList({
                pageNum: 1,
                pageSize: 9999
            }).then(res => {
                if (res) {
                    this.deviceList = res.bus_json.items;
                }
            });
        },
        // 分页器公共方法
        paginationDataNew(sth) {
            this.paginationData = sth;
            this.getListData();
        },
        //table增加按钮点击
        addNewOne() {
            this.addForm = {
                name: "",
                login_name: "",
                show_password: "",
                role_ids: "",
                turn_ids: "",
                unit: ""
            };
            if (this.tableId) {
                this.addshow = true;
                this.addForm.unit = this.tableName;
            } else {
                this.$message({
                    message: "请选择一个机构",
                    type: "info"
                });
            }
        },
        // 新增提交
        addcommit: util.debounce(function () {

            this.$refs["addForm"].validate(valid => {
                if (valid) {
                    if (this.flag) {
                        api.saveUser({
                            user_name: this.addForm.name,
                            login_name: this.addForm.login_name,
                            show_password: this.addForm.show_password,
                            role_ids: this.addForm.role_ids.length > 0 && this.addForm.role_ids.join(";"),
                            turn_ids: this.addForm.turn_ids,
                            unit: this.addForm.unit,
                            user_id: "",
                            unit_id: this.tableId
                        }).then(res => {
                            if (res) {
                                this.addshow = false;
                                this.$message({
                                    message: res.error_msg,
                                    type: "success"
                                });
                                this.getListData();
                                setTimeout(() => {
                                    this.flag = true;
                                }, 1500);
                            }
                        });
                    }
                }
            });
        }),
        // 获取dialog内角色列表list
        getRoleList_unit() {
            api.getRoleList_unit({}).then(res => {
                if (res) {
                    this.roleJson = res.bus_json;
                }
            });
        },
        // 所有关闭dialog的清除验证的回调
        dialogClose(formName) {
            this.$nextTick(() => {
                this.$refs[formName].resetFields();
            });
        },
        // table内修改按钮点击获取详情
        editNewOne(sth) {
            this.editForm = {
                name: "",
                login_name: "",
                show_password: "",
                role_ids: [],
                turn_ids: "",
                unit: "",
                user_id: "",
                unit_id: ""
            }
            api
                .getEditUser({
                    unit_id: this.tableId,
                    user_id: sth.user_id
                })
                .then(res => {
                    if (res) {
                        for (
                            let i = 0;
                            i < res.bus_json.roles.length;
                            i++
                        ) {
                            this.editForm.role_ids.push(
                                res.bus_json.roles[i].role_id
                            );
                        }
                        // for (
                        //     let i = 0;
                        //     i < res.bus_json.turns.length;
                        //     i++
                        // ) {
                        //     this.editForm.turn_ids.push(
                        //         res.bus_json.turns[i].turn_id
                        //     );
                        // }
                        this.editForm.turn_ids = res.bus_json.turn_ids;
                        this.editForm.name = res.bus_json.user_name;
                        this.editForm.login_name = res.bus_json.login_name;
                        this.editForm.show_password = res.bus_json.show_password;
                        this.editForm.unit = res.bus_json.unit_name;
                        this.editForm.unit_id = res.bus_json.unit_id;
                        this.editForm.user_id = res.bus_json.user_id;
                        this.editshow = true;
                    }
                });
        },
        // 修改dialog保存按钮点击
        editcommit: util.debounce(function () {
            this.$refs["editForm"].validate(valid => {
                if (valid) {
                    if (this.flag) {
                        api.saveUser({
                            user_name: this.editForm.name,
                            login_name: this.editForm.login_name,
                            show_password: this.editForm.show_password,
                            role_ids: this.editForm.role_ids.length > 0 && this.editForm.role_ids.join(";"),
                            turn_ids: this.editForm.turn_ids,
                            unit: this.editForm.unit,
                            user_id: this.editForm.user_id,
                            unit_id: this.editForm.unit_id
                        }).then(res => {
                            if (res) {
                                this.editshow = false;
                                this.$message({
                                    message: res.error_msg,
                                    type: "success"
                                });
                                this.getListData();
                                setTimeout(() => {
                                    this.flag = true;
                                }, 1500);
                            }
                        });
                    }
                }
            });
        }),
        operGxsb(row) {
            this.currentRow = row;
            this.getTurnList(row.user_id);
            this.getDeviceList();
            api.getTurnDevice({ user_id: row.user_id }).then(res => {
                if (res && res.error_code == 0) {
                    this.gxsbForm.gxsbData = res.bus_json;
                    this.gxsbshow = true;
                }
            });
        },
        addEmptyItem() {
            let emptyItem = {
                turn_id: "",
                device_id: ""
            };
            this.gxsbForm.gxsbData.push(emptyItem);
        },
        insertGxsb() {
            this.$refs["gxsbForm"].validate(valid => {
                if (valid) {
                    const param = {
                        user_id: this.currentRow.user_id,
                        turnDevices: this.gxsbForm.gxsbData
                    };
                    api.saveTurnDevice(param).then(res => {
                        if (res && res.error_code == 0) {
                            this.$message({
                                message: res.error_msg,
                                type: "success"
                            });
                            this.gxsbshow = false;
                        }
                    });
                }
            });
        },
        deleteGxsb(row) {
            this.gxsbForm.gxsbData.forEach((item, index, arr) => {
                if (item == row) {
                    arr.splice(index, 1);
                }
            });
        },
        // table内删除按钮点击
        deleteOne(sth) {
            this.$confirm("确认删除该数据？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    api.deleteUser({
                        user_id: sth.user_id
                    }).then(res => {
                        if (res) {
                            this.$message({
                                type: "success",
                                message: res.error_msg
                            });
                            this.getListData();
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "未删除"
                    });
                });
        },
        // table重置密码点击
        resetOne(sth) {
            this.resetForm = {
                password: "",
                passwordAgain: "",
                user_id: sth.user_id
            };
            if (this.resetForm.user_id) {
                this.resetshow = true;
            }
        },
        // 重置密码按钮提交
        resetPass() {
            if (this.resetForm) {
                if (this.resetForm.password == this.resetForm.passwordAgain) {
                    if (this.flag) {
                        api.resetPass({
                            password: this.resetForm.password,
                            user_id: this.resetForm.user_id
                        }).then(res => {
                            if (res) {
                                this.$message({
                                    type: "success",
                                    message: res.error_msg
                                });
                                this.getListData();
                                this.resetshow = false;
                                setTimeout(() => {
                                    this.flag = true;
                                }, 1500);
                            }
                        });
                    }
                } else {
                    this.$message({
                        type: "info",
                        message: "密码和确认密码不匹配"
                    });
                }
            } else {
                this.$message({
                    type: "info",
                    message: "请输入密码以及确认密码"
                });
            }
        },
        //table内禁用/启用按钮点击
        disableItem(sth) {
            this.disableForm.msg = sth.state == 0 ? "启用" : "禁用";
            this.disableForm.user_id = sth.user_id;
            this.disableForm.state = sth.state;
            this.$confirm(`是否确认${this.disableForm.msg}该用户？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    api.setState({
                        state: this.disableForm.state == 0 ? 1 : 0,
                        user_id: this.disableForm.user_id
                    }).then(res => {
                        if (res) {
                            this.$message({
                                type: "success",
                                message: res.error_msg
                            });
                            this.getListData();
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: `未${this.disableForm.msg}`
                    });
                });
        },
        // 请求codelist接口，获取角色类型
        getRoleTypeList() {
            api.getCodelistByKind({
                code_kind: "user_type"
            }).then(res => {
                if (res) {
                    this.typeJson = res.bus_json[0].codelists;
                }
            });
        }
    },
    created() { },
    mounted() {
        this.getTableId();
        this.getHuanjie();
        this.getRoleList_unit();
        this.getRoleTypeList();
        this.screenWidth = document.body.clientWidth;
        window.onresize = () => {
            this.screenWidth = document.body.clientWidth;
        };
    },
    // destroyed () {

    // },
    watch: {
        tableId() {
            (this.paginationData = {
                pageNum: "1",
                pageSize: "10",
                totalNum: ""
            }),
                this.getListData();
        },
        screenWidth(val) {
            if (val > 1500) {
                this.screen = true;
            } else if (val < 1500) {
                this.screen = false;
            }
        }
    }
};
</script>
<style lang="scss">
.institutions_table {
    padding: 0 20px 0 0;

    .inputCont {
        width: 100%;
        display: inline-flex;
        margin: 20px 0 0 0;

        .demo-form-inline {
            width: calc(100% - 200px);
        }
    }

    .btn_container {
        text-align: right;
        margin-bottom: 10px;
    }
}

.gxsbTable {
    .el-form-item {
        margin-bottom: 0;
    }

    .el-form-item__content {
        margin-left: 0 !important;
    }
}
</style>
